<template>
    <div>
        <div class="container">
            <div class="title">api</div>
            <div><input type="text" v-model="data.host" /></div>

            <div class="title">username</div>
            <div><input type="text" v-model="data.username" /></div>

            <div class="title">password</div>
            <div><input type="password" v-model="data.password" /></div>

            <div class="title">token_age</div>
            <div><input type="number" v-model="data.age" />天</div>

            <template v-if="expired">
                <div></div>
                <div>{{ expired }}过期</div>
            </template>

            <div></div>
            <div>
                <button class="action" @click="clearLogin">清除登录</button>
                <button class="action" @click="login">登录</button>
            </div>
        </div>
        <div class="tips">
            <p>api:接口地址（如：http://127.0.0.1/api,不带最后的“/”）</p>
        </div>
    </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { onMounted, reactive, ref } from "vue";
import { storage } from "wxt/storage";

const data = reactive({ host: "", username: "", password: "", age: 333, token_age: 0 });
const expired = ref("");

const clearLogin = async () => {
    await storage.removeItem("local::_token");
};

onMounted(async () => {
    expired.value = (await storage.getItem("local:_token_expired")) || "";
});

const login = async () => {
    data.token_age = data.age * 3600 * 24;
    let resp = await axios.post(data.host + "/login", data);
    let res = resp.data;
    if (res.errcode == 0) {
        let date = new Date();
        date.setDate(date.getDate() + data.age);
        expired.value = date.toLocaleString();
        await storage.setItem("local:_token_expired", expired.value);
        await storage.setItem("local:host", data.host);
        await storage.setItem("session:host", data.host);
        await storage.setItem("local:_token", res.data._token);
        data.host = "";
        data.username = "";
        data.password = "";
        data.age = 333;
    } else {
        alert(res.errMsg);
    }
};
</script>

<style scoped>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-size: 18px;
}

.container {
    height: auto;
    width: 100%;
    display: grid;
    grid-template-columns: fit-content(100px) 1fr;
    column-gap: 10px;
    row-gap: 10px;
    justify-items: end start;
}

.title {
    justify-self: end;
}

.action {
    padding: 5px 15px;
    margin: 5px;
}

.tips {
    margin-top: 33px;
}
</style>
